#include "util_com.h"
#include "rtdevice.h"

static rt_device_t serial;
static int mode = COM_MODE_MASTER;
static rt_sem_t rx_sem;

static cmd_callback_t cmd_callback;

static rt_err_t _on_recv(rt_device_t dev, rt_size_t size)
{
    rt_sem_release(rx_sem);
    return RT_EOK;
}
static void _serial_parse_thread(void *para)
{
    rt_uint8_t cmd;
    while (1)
    {
        rt_sem_take(rx_sem, RT_WAITING_FOREVER);
        if (rt_device_read(serial, 0, &cmd, 1))
        {
            cmd_callback(cmd);
        }
    }
}

void ist_com_init(rt_device_t _serial, int _mode)
{
    serial = _serial;
    mode = _mode;

    rx_sem = rt_sem_create("com_rx_sem", 0, RT_IPC_FLAG_FIFO);

    // 设置串口回调函数

    rt_device_set_rx_indicate(serial, _on_recv);

    rt_thread_t thread = rt_thread_create("com_parse", _serial_parse_thread, RT_NULL, 512, 8, 10);
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
}

void ist_com_send(rt_uint8_t cmd)
{
    if (mode == COM_MODE_MASTER)
    {
        rt_device_write(serial, 0, &cmd, 1);
    }
}
